import 'dart:async';
import 'dart:io';

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class PipelineDatabase {
  PipelineDatabase._();

  static final PipelineDatabase _instance = PipelineDatabase._();

  factory PipelineDatabase() {
    return _instance;
  }

  static const _DBPATH = "pipeline.db";
  late Database _db;

  Database get db => _db;

  Future<Database> open() async {
    _db = await openDatabase(_DBPATH, version: 1);
    return _db;
  }

  /// 重置
  Future<String> restore(String dbName) async {
    final databasePath = await getDatabasesPath();
    final path = join(databasePath, dbName);
    if (await Directory(dirname(path)).exists()) {
      await deleteDatabase(path);
    } else {
      try {
        await Directory(dirname(path)).create(recursive: true);
      } catch (e) {}
    }
    return path;
  }

  Future<void> close() async => _db.close();
}
